package cn.dongqihong.framework.imgcode;

import org.apache.log4j.Logger;

import java.awt.*;
import java.io.File;
import java.net.URLDecoder;

/**
 * 图形验证码字体
 *
 * @author DongQihong
 */
public class ImgFont {
    private static Logger logger = Logger.getLogger(ImgFont.class);
    private volatile static ImgFont imgFontByte;
    private String path = null;
    private File fontFile = null;

    private ImgFont() {
        path = ImgFont.class.getResource("/ImgCode.ttf").getFile();
        try {
            path = URLDecoder.decode(path, "utf-8");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        fontFile = new File(path);
    }

    /**
     * 获取验证码字体
     * @return 验证码字体
     */
    public static ImgFont getInstance() {
        if (imgFontByte == null){
            synchronized (ImgFont.class){
                if(imgFontByte == null){
                    imgFontByte = new ImgFont();
                }
            }
        }
        return imgFontByte;
    }

    /**
     * 获取字体
     *
     * @param fontHeight 字体高
     * @return 字体
     */
    public Font getFont(int fontHeight) {
        try {
            Font baseFont = Font.createFont(Font.TRUETYPE_FONT, fontFile);
            return baseFont.deriveFont(Font.PLAIN, fontHeight);
        } catch (Exception e) {
            return new Font("Arial", Font.PLAIN, fontHeight);
        }
    }
}
